package com.shqcjd.sinopecdemomobile.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.AllTaskBean;
import com.shqcjd.sinopecdemomobile.model.pojo.InspectionListBean;
import com.shqcjd.sinopecdemomobile.ui.adapter.TrajectoryAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.Config;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class TrajectoryActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    private static final int PAGE_SIZE = 6;
    private int mNextRequestPage = 1;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;
    @BindView(R.id.iv_toolbar_back)
    ImageView ivToolbarBack;
    @BindView(R.id.tv_toolbar_center)
    TextView tvToolbarCenter;
    private TrajectoryAdapter trajectoryAdapter;
    private View notDataView;
    private Context mContext;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_trajectory;
    }

    @Override
    public void initView() {
        mContext = this;
        tvToolbarCenter.setText("巡检轨迹");
        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvList.getParent(), false);
        trajectoryAdapter = new TrajectoryAdapter();
        rvList.setLayoutManager(new LinearLayoutManager(this));
        rvList.setAdapter(trajectoryAdapter);
        swipeRefresh.setOnRefreshListener(this);
        trajectoryAdapter.setOnLoadMoreListener(this,rvList);
        trajectoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                RxPermissions permissions = new RxPermissions(TrajectoryActivity.this);
                permissions.setLogging(true);
                permissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    InspectionListBean.ListBean item = (InspectionListBean.ListBean) adapter.getItem(position);
                                    Intent it = new Intent(mContext,TrajectoryDetailsActivity.class);
                                    it.putExtra("taskId", item.taskId);
                                    startActivity(it);
                                } else {
                                    ToastUtils.show(TrajectoryActivity.this, "巡检需要获取定位的权限", Toast.LENGTH_SHORT);
                                }
                            }
                        });
            }
        });

    }

    @Override
    public void initData() {
        refresh();
    }

    private void refresh(){
        mNextRequestPage = 1;
        trajectoryAdapter.setEnableLoadMore(false);
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex",mNextRequestPage+"");
        map.put("pageSize", Config.PAGE_TOTAL+"");
        map.put("state",1+"");//1待巡检  2已巡检
        map.put("searchContent","");

        ApiService.getInspectionList(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<InspectionListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        showRefreshView(true);
                    }

                    @Override
                    public void _onNext(ResponseData<InspectionListBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            setData(true, retData.data.list);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }

                    }

                    @Override
                    public void _onError(String errorMessage) {
                        trajectoryAdapter.setEnableLoadMore(true);
                        showRefreshView(false);
                    }

                    @Override
                    public void _onComplete() {
                        trajectoryAdapter.setEnableLoadMore(true);
                        showRefreshView(false);
                    }
                });
    }

    private void loadMore() {

        Map<String, String> map = new HashMap<>();
        map.put("pageIndex",mNextRequestPage+"");
        map.put("pageSize", Config.PAGE_TOTAL+"");
        map.put("state",1+"");//1待巡检  2已巡检
        map.put("searchContent","");

        ApiService.getInspectionList(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<InspectionListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<InspectionListBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            boolean isRefresh =mNextRequestPage ==1;
                            setData(isRefresh, retData.data.list);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        trajectoryAdapter.loadMoreFail();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }


    public void showRefreshView(Boolean refresh) {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(refresh);
            }
        });
    }

    private void setData(boolean isRefresh, List data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (size > 0) {
                trajectoryAdapter.setNewData(data);
            } else {
                trajectoryAdapter.setNewData(null);
                trajectoryAdapter.setEmptyView(notDataView);
            }
        } else {
            if (size > 0) {
                trajectoryAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            trajectoryAdapter.loadMoreEnd(isRefresh);
        } else {
            trajectoryAdapter.loadMoreComplete();
        }
    }

    @OnClick(R.id.iv_toolbar_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onRefresh() {
        refresh();
    }


    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }
}
